<template>
  <div class="secondhand-container">
    <!-- 加载状态 -->
    <div v-if="loading && pageNum === 1" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 商品列表 -->
    <div v-else class="goods-list">
      <div v-for="item in goodsList" :key="item.itemID" class="goods-item" @click="goToDetail(item.itemID)">
        <div class="goods-image" :style="{ backgroundImage: `url(${item.imageUrl || defaultImage})` }">
          <div class="goods-price">¥{{ item.price }}</div>
        </div>
        <div class="goods-info">
          <h3 class="goods-title">{{ item.title }}</h3>
          <p class="goods-desc">{{ item.description }}</p>
          <div class="goods-meta">
            <div class="goods-status">
              <el-tag size="small" :type="getStatusType(item.status)">{{ getStatusText(item.status) }}</el-tag>
            </div>
            <div class="goods-time">{{ formatTime(item.createTime) }}</div>
          </div>
          <div class="user-seller-row">
            <div class="user-info" @click.stop="goToUserProfile(item.sellerID)">
              <div class="user-avatar" :style="{ backgroundImage: `url(${item.sellerAvatar || defaultAvatar})` }"></div>
              <span class="user-name">{{ item.sellerName || '用户' + item.sellerID }}</span>
            </div>
            <div class="action-buttons">
              <span class="more-options" @click.stop="openReportDialog(item)">
                <el-icon><MoreFilled /></el-icon>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="goodsList.length === 0" class="empty-state">
        <el-empty description="暂无商品" />
      </div>
    </div>

    <!-- 加载更多指示器 -->
    <div v-if="loading && pageNum > 1" class="loading-more">
      <el-skeleton :rows="1" animated />
    </div>

    <!-- 没有更多数据提示 -->
    <div v-if="!loading && noMoreData" class="no-more-data">
      没有更多商品了
    </div>

    <!-- 添加举报对话框 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="举报商品"
      width="30%"
      :before-close="handleReportDialogClose"
    >
      <div class="report-dialog-content">
        <p>请选择举报原因：</p>
        <el-radio-group v-model="reportReason" class="report-reason-group">
          <el-radio label="虚假商品">虚假商品</el-radio>
          <el-radio label="价格虚高">价格虚高</el-radio>
          <el-radio label="违禁产品">违禁产品</el-radio>
          <el-radio label="广告欺诈">广告欺诈</el-radio>
          <el-radio label="涉嫌盗版">涉嫌盗版</el-radio>
          <el-radio label="其他">其他</el-radio>
        </el-radio-group>
        
        <div v-if="reportReason === '其他'" class="report-other-reason">
          <el-input
            v-model="reportOtherReason"
            type="textarea"
            placeholder="请详细描述举报原因"
            maxlength="200"
            show-word-limit
            :rows="3"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleReportDialogClose">取消</el-button>
          <el-button type="primary" @click="submitReport" :disabled="!canSubmitReport">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue';
import { Location, MoreFilled } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { SecondHandItemApi } from '@/api/SecondHandItemApi.js';
import { MarketItemApi } from '@/api/new/MarketItemApi.ts';
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import { ElMessage } from 'element-plus';
import UserUtil from '@/utils/User/User.js';

const router = useRouter();
const sortBy = ref('newest');
const goodsList = ref([]);
const loading = ref(true);

// 分页参数
const pageNum = ref(1);
const pageSize = ref(20);
const noMoreData = ref(false);

// 默认图片
const defaultImage = 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png';
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 作者信息缓存
const sellerCache = ref({});

// 获取卖家信息
const fetchSellerInfo = async (sellerId) => {
  // 如果缓存中已有该卖家信息，直接返回
  if (sellerCache.value[sellerId]) {
    return sellerCache.value[sellerId];
  }
  
  try {
    // 使用UserProfileApi获取用户信息
    const userData = await UserProfileApi.getUserInfo(sellerId);
    
    // 缓存卖家信息
    sellerCache.value[sellerId] = {
      username: userData.username || '未知用户',
      headshot: userData.headshot || defaultAvatar
    };
    
    return sellerCache.value[sellerId];
  } catch (error) {
    console.error(`获取卖家 ${sellerId} 信息失败:`, error);
    // 返回默认信息
    return {
      username: '未知用户',
      headshot: defaultAvatar
    };
  }
};

// 获取商品列表
const fetchGoodsList = async (isFirstLoad = true) => {
  try {
    // 使用MarketItemApi.searchItems进行分页查询
    const res = await MarketItemApi.searchItems('', pageNum.value, pageSize.value);
    const response = JSON.parse(res);
    const items = response.data || [];
    
    // 如果返回的数据为空数组，说明没有更多数据了
    if (items.length === 0) {
      noMoreData.value = true;
      return;
    }

    // 如果返回的数据少于请求的数量，说明这是最后一页
    if (items.length < pageSize.value) {
      noMoreData.value = true;
    }
    
    // 获取每个商品的第一张图片和卖家信息
    const itemsWithDetails = await Promise.all(
      items.map(async (item) => {
        try {
          // 并行获取商品图片和卖家信息
          const [imageResponse, sellerInfo] = await Promise.all([
            MarketItemApi.getItemImages(item.itemID),
            fetchSellerInfo(item.sellerID)
          ]);
          
          let imageUrl = defaultImage;
          
          // 检查返回的图片数据
          if (imageResponse && Array.isArray(imageResponse) && imageResponse.length > 0) {
            // 使用第一张图片
            imageUrl = imageResponse[0].imageUrl;
          } else if (imageResponse && imageResponse.imageUrl) {
            // 如果直接返回单个图片对象
            imageUrl = imageResponse.imageUrl;
          } else if (imageResponse && imageResponse.data && imageResponse.data.imageUrl) {
            // 嵌套数据结构
            imageUrl = imageResponse.data.imageUrl;
          }
          
          return {
            ...item,
            imageUrl,
            sellerName: sellerInfo.username,
            sellerAvatar: sellerInfo.headshot,
            createTime: item.creationTime || new Date().toISOString()
          };
        } catch (error) {
          console.error(`获取商品 ${item.itemID} 详情失败:`, error);
          return {
            ...item,
            imageUrl: defaultImage,
            sellerName: '未知用户',
            sellerAvatar: defaultAvatar,
            createTime: item.creationTime || new Date().toISOString()
          };
        }
      })
    );
    
    // 应用默认排序 - 最新发布
    const sortedItems = [...itemsWithDetails].sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    
    // 如果是首次加载，替换列表；否则追加到列表
    if (isFirstLoad) {
      goodsList.value = sortedItems;
    } else {
      goodsList.value = [...goodsList.value, ...sortedItems];
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败，请稍后重试');
    if (isFirstLoad) {
      goodsList.value = [];
    }
  } finally {
    loading.value = false;
  }
};

// 加载更多商品
const loadMoreGoods = async () => {
  if (loading.value || noMoreData.value) return;
  
  // 如果是首次加载，不增加页码
  if (pageNum.value === 1 && goodsList.value.length === 0) {
    await fetchGoodsList(true);
    return;
  }
  
  loading.value = true;
  
  try {
    // 增加页码
    pageNum.value++;
    
    // 调用API获取下一页数据
    await fetchGoodsList(false);
  } catch (error) {
    console.error('加载更多商品失败:', error);
    ElMessage.error('加载更多商品失败，请稍后再试');
    // 失败时恢复页码
    pageNum.value--;
  } finally {
    loading.value = false;
  }
};

// 手动检查滚动位置
const checkScrollPosition = () => {
  // 如果已经没有更多数据或正在加载，则不处理
  if (loading.value || noMoreData.value) return;
  
  const scrollHeight = document.documentElement.scrollHeight;
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const clientHeight = document.documentElement.clientHeight;
  
  // 如果滚动到距离底部100px以内，触发加载更多
  if (scrollHeight - scrollTop - clientHeight < 100) {
    loadMoreGoods();
  }
};

// 添加滚动事件监听
const addScrollListener = () => {
  window.addEventListener('scroll', checkScrollPosition);
};

// 移除滚动事件监听
const removeScrollListener = () => {
  window.removeEventListener('scroll', checkScrollPosition);
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间';
  
  const now = new Date();
  const time = new Date(timeStr);
  const diff = Math.floor((now - time) / 1000); // 秒数差
  
  if (diff < 60) {
    return '刚刚';
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + '分钟前';
  } else if (diff < 86400) {
    return Math.floor(diff / 3600) + '小时前';
  } else if (diff < 2592000) {
    return Math.floor(diff / 86400) + '天前';
  } else {
    return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}`;
  }
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'forSale':
      return '';
    case 'inTransaction':
      return 'warning';
    case 'sold':
      return 'info';
    default:
      return '';
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'forSale':
      return '在售';
    case 'inTransaction':
      return '已预订';
    case 'sold':
      return '已售出';
    default:
      return '未知';
  }
};

// 跳转到详情页
const goToDetail = (itemID) => {
  router.push(`/secondhand/detail/${itemID}`);
};

// 跳转到用户个人页面
const goToUserProfile = (userId) => {
  if (!userId) return;
  
  router.push({
    path: '/otherUser',
    query: { userId }
  });
};

// 举报相关状态
const reportDialogVisible = ref(false);
const reportReason = ref('');
const reportOtherReason = ref('');
const reportingItemId = ref(null);

// 计算属性：是否可以提交举报
const canSubmitReport = computed(() => {
  if (!reportReason.value) return false;
  if (reportReason.value === '其他' && !reportOtherReason.value.trim()) return false;
  return true;
});

// 打开举报对话框
const openReportDialog = (item) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();

  // 检查用户是否登录
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录后再举报');
    return;
  }

  reportingItemId.value = item.itemID;
  reportReason.value = '';
  reportOtherReason.value = '';
  reportDialogVisible.value = true;
};

// 关闭举报对话框
const handleReportDialogClose = () => {
  reportDialogVisible.value = false;
  reportReason.value = '';
  reportOtherReason.value = '';
  reportingItemId.value = null;
};

// 提交举报
const submitReport = async () => {
  if (!canSubmitReport.value) return;

  try {
    // 准备举报原因
    const finalReason = reportReason.value === '其他'
      ? reportOtherReason.value
      : reportReason.value;

    // 调用举报API - 使用MarketItemApi
    await MarketItemApi.reportItem(reportingItemId.value, finalReason);

    ElMessage.success('举报已提交，感谢您的反馈');
    handleReportDialogClose();
  } catch (error) {
    console.error('举报失败:', error);
    ElMessage.error(`举报失败: ${error.message || '未知错误'}`);
  }
};

// 页面加载时获取商品列表并添加滚动监听
onMounted(() => {
  fetchGoodsList(true);
  addScrollListener();
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  removeScrollListener();
});
</script>

<style lang="less" scoped>
.secondhand-container {
  padding: 24px;
  background-color: #fafafa;
  min-height: calc(100vh - 72px);
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.loading-more {
  padding: 20px;
  margin-top: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.no-more-data {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.goods-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .goods-image {
    height: 200px;
    background-size: cover;
    background-position: center;
    position: relative;
    background-color: #f5f5f5;

    .goods-price {
      position: absolute;
      bottom: 0;
      left: 0;
      background: rgba(255, 36, 66, 0.9);
      color: white;
      padding: 4px 12px;
      font-weight: bold;
      border-top-right-radius: 8px;
      font-size: 16px;
    }
  }

  .goods-info {
    padding: 16px;

    .goods-title {
      margin: 0 0 8px;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .goods-desc {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      height: 42px;
    }

    .goods-meta {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: #999;
      margin-bottom: 12px;
    }

    .user-seller-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 12px;
      
      .user-info {
        display: flex;
        align-items: center;
        transition: opacity 0.2s;
        cursor: pointer;
        
        &:hover {
          opacity: 0.8;
        }
        
        .user-avatar {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background-size: cover;
          background-position: center;
          margin-right: 8px;
          background-color: #eee;
          border: 1px solid rgba(0, 0, 0, 0.08);
        }
        
        .user-name {
          font-size: 13px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      
      .action-buttons {
        .more-options {
          cursor: pointer;
          color: #999;
          padding: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          transition: all 0.2s;
          
          &:hover {
            color: #666;
            background-color: #f5f5f5;
          }
        }
      }
    }
  }
}

.empty-state {
  grid-column: 1 / -1;
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .goods-list {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
  }

  .goods-item {
    .goods-image {
      height: 140px;
    }

    .goods-info {
      padding: 10px;

      .goods-title {
        font-size: 14px;
      }

      .goods-desc {
        font-size: 12px;
        height: 36px;
      }
    }
  }
}

// 举报对话框样式
.report-dialog-content {
  p {
    margin-bottom: 16px;
    font-weight: bold;
  }
  
  .report-reason-group {
    display: grid;
    grid-template-columns: repeat(2, 1fr); // 两列布局
    grid-gap: 15px 20px; // 行间距15px，列间距20px
    
    @media (min-width: 768px) {
      grid-template-columns: repeat(3, 1fr); // 在大屏上用三列布局
    }
  }
  
  .report-other-reason {
    margin-top: 16px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 自定义Element Plus对话框样式
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .el-dialog__body {
    padding: 24px;
  }
  
  .el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
  }
}

// 自定义Element Plus单选框样式
:deep(.el-radio) {
  margin-right: 0;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .el-radio__input.is-checked + .el-radio__label {
    font-weight: bold;
  }
}

// 自定义文本输入框样式
:deep(.el-textarea) {
  .el-textarea__inner {
    border-radius: 8px;
    transition: all 0.3s;
    
    &:focus {
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
    }
  }
}

// 自定义按钮样式
:deep(.el-button) {
  border-radius: 8px;
  
  &.el-button--primary {
    box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
  }
}
</style>
